
import { useState, useRef, useEffect } from 'react';
import MarkdownIt from 'markdown-it';
import DOMPurify from 'dompurify';
import './App.css';
import Preview from './Preview'; // Import the new Preview component

// Initialize markdown-it
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
});

// Override the default renderer for strong (bold) tags
const defaultStrongOpen = md.renderer.rules.strong_open || function(tokens, idx, options, env, self) {
  return self.renderToken(tokens, idx, options);
};
const defaultStrongClose = md.renderer.rules.strong_close || function(tokens, idx, options, env, self) {
  return self.renderToken(tokens, idx, options);
};

md.renderer.rules.strong_open = function (tokens, idx, options, env, self) {
  // Add the 'highlight' class to the strong tag
  tokens[idx].attrJoin('class', 'highlight');
  return defaultStrongOpen(tokens, idx, options, env, self);
};

md.renderer.rules.strong_close = function (tokens, idx, options, env, self) {
  return defaultStrongClose(tokens, idx, options, env, self);
};

const initialMarkdown = `# Welcome!\n\nThis content is long enough to demonstrate the pagination feature.\n\n## Section 1\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices diam. Maecenas ligula massa, varius a, semper congue, euismod non, mi. \n\n## Section 2\n\nProin porttitor, orci nec nonummy molestie, enim est eleifend mi, non fermentum diam nisl sit amet erat. Duis semper. Duis arcu massa, scelerisque vitae, consequat in, pretium a, enim. Pellentesque congue. Ut in risus volutpat libero pharetra tempor. \n\n'''javascript\n// This is a code block\nfunction fib(n) {\n  if (n <= 1) return n;\n  return fib(n - 1) + fib(n - 2);\n}\n\nconsole.log("This might push to a new page!");\n'''\n\n## Section 3\n\nCras mattis, est eget pretium imperdiet, sapien massa blandit diam, quis blandit odio lorem non neque. Praesent vitae hulsm. In laoreet, magna id viverra tincidunt, sem odio bibendum justo, vel imperdiet sapien wisi sed libero. Suspendisse sagiverra, at sodales eros.\n\n![test image](https://via.placeholder.com/300x200)

This should definitely be on a new page now.

Here is an image from the 'public' folder:

![Vite Logo](/vite.svg)
`;

function App() {
  const [markdown, setMarkdown] = useState(initialMarkdown);
  
  const fileInputRef = useRef(null);
  const textareaRef = useRef(null); // Ref for the textarea

  

  const handleInputChange = (e) => {
    setMarkdown(e.target.value);
  };

  const handleImageUploadClick = () => {
    fileInputRef.current.click();
  };

  const handleFileChange = async (e) => { // Make it async
    const file = e.target.files[0];
    if (!file || !textareaRef.current) {
      return;
    }

    const formData = new FormData();
    formData.append('image', file); // 'image' must match the field name in multer's upload.single('image')

    try {
      const response = await fetch('http://localhost:3001/upload', { // Backend upload endpoint
        method: 'POST',
        body: formData,
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      const imageUrl = data.url; // Get the URL from the backend response

      const markdownToInsert = `
![${file.name}](${imageUrl})
`;
      
      const textarea = textareaRef.current;
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;

      const newText = 
        markdown.substring(0, start) + 
        markdownToInsert + 
        markdown.substring(end);

      setMarkdown(newText);

      setTimeout(() => {
        textarea.focus();
        textarea.selectionStart = textarea.selectionEnd = start + markdownToInsert.length;
      }, 0);

    } catch (error) {
      console.error('Error uploading image:', error);
      alert('Failed to upload image. Check console for details.');
    }
  };

  // Sanitize HTML, allowing blob and data URLs for our local images
  const sanitizedHtml = DOMPurify.sanitize(md.render(markdown), {
    ALLOWED_URI_SCHEMES: ['http', 'https', 'data', 'blob'],
  });

  return (
    <div className="app-layout">
      <div className="preview-pane">
        <Preview htmlContent={sanitizedHtml} />
      </div>
      <div className="editor-pane">
        <div className="editor-toolbar">
          <button onClick={handleImageUploadClick} className="editor-button">
            Insert Local Image
          </button>
          <input
            type="file"
            ref={fileInputRef}
            onChange={handleFileChange}
            style={{ display: 'none' }}
            accept="image/*"
          />
        </div>
        <textarea
          ref={textareaRef} // Attach the ref
          className="markdown-textarea"
          value={markdown}
          onChange={handleInputChange}
          aria-label="Markdown Input"
        />
      </div>
    </div>
  );
}

export default App;
